package com.chaochis.springboottestdemo.controller;


import com.chaochis.springboottestdemo.base.ApiResult;
import com.chaochis.springboottestdemo.config.reqResConfig.dispatcherConfig.CustomRequestWrapper;
import com.chaochis.springboottestdemo.enumList.ApiCode;
import com.chaochis.springboottestdemo.exception.TokenExpiredException;
import com.chaochis.springboottestdemo.model.apiResultVo.ApiUser;
import com.chaochis.springboottestdemo.model.mapperModel.UserVo;
import com.chaochis.springboottestdemo.model.queryParam.UserParam;
import com.chaochis.springboottestdemo.service.CacheRedisUserService;
import com.chaochis.springboottestdemo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

@RestController("user")
@RequestMapping("/user")
public class UserController {

  private final UserService userService;
  private final CacheRedisUserService cacheRedisUserService;

  public UserController(UserService userService, CacheRedisUserService cacheRedisUserService) {
    this.userService = userService;
    this.cacheRedisUserService = cacheRedisUserService;
  }

  @GetMapping("/getList")
  public ApiResult getUserList(UserParam userParam){
    var userVo = new UserVo();
    BeanUtils.copyProperties(userParam, userVo);
    var list = this.userService.getAllList(userVo);
    return ApiResult.ok(list);
  }

  @GetMapping("/getUserByToken")
  public ApiResult getUserByToken(@ApiIgnore CustomRequestWrapper customRequestWrapper) {
    ApiUser user = null;
    try{
      user = this.cacheRedisUserService.getUserInfoByToken(customRequestWrapper.getRequestInfo().getAuthToken().getToken());
    } catch (TokenExpiredException e) {
      return ApiResult.build(null, ApiCode.TokenExpired, e);
    } catch (Exception e) {
      return ApiResult.fail(e);
    }
    return ApiResult.ok(user);
  }

}
